package com.study.order_service.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.study.order_service.service.ProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: LWM
 * @date: 2019/2/20
 * @time: 12:02
 * Description: No Description
 */
@Controller
@RestController
@RequestMapping("api/v1/order")
public class ProductOrderController {
    @Autowired
    private ProductOrderService productOrderService;
    /*@Autowired
    private StringRedisTemplate redisTemplate;*/
    /**
     * 下单
     * @return
     */
    @RequestMapping("save")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(@RequestParam("user_id") int userId, @RequestParam("product_id") int productId, HttpServletRequest request){
        HashMap<String, Object> msg = new HashMap<>();
        msg.put("code",1);
        msg.put("msg",productOrderService.save(userId,productId));
        return msg;
    }

    /**
     * 熔断 降级返回 可以采用兜底数据
     * 方法签名需要与api方法一致
     * @param userId
     * @param productId
     * @return
     */
    public Object saveOrderFail(int userId,int productId,HttpServletRequest request){
       /* //监控报警
        String saveOrderKye = "save-order";
        String sendValue = redisTemplate.opsForValue().get(saveOrderKye);
        final String ip = request.getRemoteAddr();
        //开启异步线程
        new Thread( ()->{
            if (StringUtils.isBlank(sendValue)) {
                System.out.println("紧急短信，用户下单失败，请离开查找原因,ip地址是="+ip);
                //发送一个http请求，调用短信服务 TODO
                //20秒后失效
                redisTemplate.opsForValue().set(saveOrderKye, "save-order-fail", 20, TimeUnit.SECONDS);
            }else{
                System.out.println("已经发送过短信，20秒内不重复发送");
            }
        }).start();*/

        HashMap<String, Object> msg = new HashMap<>();
        msg.put("code",-1);
        msg.put("msg","当前人数过多,请稍后再试!");
        return msg;
    }
}
